package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 *  shiro认证操作
 *  1. Subject
 */
public class App {
    public static void main(String[] args) {


        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // 安全管理器  注入realm对象
        IniRealm realm = new IniRealm("classpath:users.ini");
        defaultSecurityManager.setRealm(realm);
        // 安全管理工具类   注入安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //安全工具类 获取认证主体  subject
        Subject subject = SecurityUtils.getSubject();
        // 认证
        String username = "root";
        String password="123456";
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        //  没有抛出异常则认证通过
        //  1.IncorrectCredentialsException  密码错误      UnknownAccountException 用户名错误
        try {
            subject.login(usernamePasswordToken);
            // 判定用户认证是否通过
            boolean authenticated = subject.isAuthenticated();
            System.out.println("authenticated = " + authenticated);
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }catch (UnknownAccountException e){
            System.out.println("用户名错误");
        }

    }
}
